<template>
  <div class="general-select">
    <el-row :gutter="20">

      <!-- 项目列表 -->
      <el-col :span="6" class="project-list">

        <el-card class="project-card" shadow="hover">
          <el-radio-group v-model="projectState" @change="projectChange" size="medium">
            <el-radio-button label="ongoing">在途项目</el-radio-button>
            <el-radio-button label="completed">已结项项目</el-radio-button>
          </el-radio-group>
          <el-table :data="tableData" style="width: 100%" stripe highlight-current-row @row-click="getDetails">
            <el-table-column prop="projectName" class-name="project-column">
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 项目详情 -->
      <el-col :span="16" v-if="projectDetails" class="project-details">
        <!-- 项目信息 -->
        <el-card class="info-card" shadow="hover">
          <div slot="header" class="card-header">
            <div>
              <h1>{{ projectDetails.projectName }} 项目成员列表</h1>
            </div>
            <div></div>
            <div><el-button type="primary" v-show="operable" @click="addVisible = true; newMember = '';">新增成员</el-button> </div>


          </div>
          <el-table :data="membersData" stripe style="width: 100%">
            <el-table-column prop="memberName" label="成员姓名">
            </el-table-column>
            <el-table-column prop="memberJob" label="职务">
            </el-table-column>
            <el-table-column prop="taskNames" label="负责任务">
            </el-table-column>
            <el-table-column prop="monthlySalary" label="月工资">
            </el-table-column>
            <el-table-column prop="email" label="联系邮箱">
            </el-table-column>
            <el-table-column prop="totalWorkHours" label="总工时">
            </el-table-column>
            <el-table-column label="操作" v-if="operable">
                <template slot-scope="scope">
                  <el-button
                      v-if="scope.row.memberJob !== '项目负责人'"
                      type="danger"
                      icon="el-icon-delete" circle
                      @click="removeMember(id, scope.row.memberId)">
                  </el-button>
                </template>
              </el-table-column>
          </el-table>
          <el-row :gutter="20">

          </el-row>
        </el-card>
        <!-- 甘特图区域 -->
        <el-card class="gantt-card" shadow="hover">
          <div slot="header" class="card-header">
            <h1>人员支撑图</h1>
          </div>
          <div class="gantt-container" ref="ganttChart"></div>
        </el-card>


      </el-col>
    </el-row>
    <el-dialog
  title="添加成员"
  :visible.sync="addVisible"
  width="30%">
  <h4>向  {{ projectDetails.projectName }}  项目中添加成员 </h4>
  <div>
    <el-select v-model="newMember" placeholder="选择成员">
                <el-option
                    v-for="member in allMembers"
                    :key="member.memberId"
                    :label="`${member.memberName} - ${member.memberJob}`"
                    :value="member.memberId">
                </el-option>
              </el-select>
  </div>
  
  <span slot="footer" class="dialog-footer">
    <el-button @click="addVisible = false">取 消</el-button>
    <el-button type="primary" @click="addVisible = false; confirmNewMember();">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>



<script>
import http from "@/api/http";
import * as echarts from 'echarts';

export default {
  name: 'ManagerMember',
  data() {
    return {
      id: 0,
      projectState: "ongoing",
      ganttChart: null,
      tableData: [],
      projectDetails: null,
      membersData: [],
      projectTasks: [],
      allMembers: [], // 所有成员信息
      newMember: '', // 新增成员信息

      addVisible: false,
      operable: true,//是否可以添加或者移除成员，关系到添加和移除按钮的显示，由于一开始进入页面时展示的是在途项目，所以是可以添加或移除的
    }
  },
  methods: {
    async getDetails(row) {
      console.log("选中的项目:", row);
      this.id = row.projectId;

      try {
        await this.fetchProjectDetails(this.id);
        await this.fetchProjectTasks(this.id);
        await this.fetchMembers(this.id)

        console.log("项目详情:", this.projectDetails);
        console.log("项目任务:", this.projectTasks);
        console.log("项目成员:", this.membersData);

        if (this.projectTasks && this.projectTasks.length > 0) {
          this.$nextTick(() => {
            this.initGanttChart();
          });
        } else {
          console.log("没有任务数据可供显示");
        }
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    },

    async fetchMembers(projectId) {
      try {
        const membersResponse = await http.get(`/api/members/${projectId}/members`);
        this.membersData = membersResponse || [];
      }
      catch (error) {
        console.error(`Error fetching members for project ${projectId}:`, error);
        this.membersData = [];
      }
    },

    projectChange() {
      if (this.projectState == "ongoing"){
        this.getOngoingProject();
        this.operable=true;
      }
        
      else if (this.projectState == "completed"){
        this.getCompletedProject();
        this.operable=false;
      }
        
      else
        console.error("Error fetching projects.");
    },

    async fetchAllMembers() {
      try {
        const membersResponse = await http.get('/api/members');
        this.allMembers = membersResponse;
      } catch (error) {
        console.error('Error fetching all members:', error);
      }
    },
    async confirmNewMember() {
      if (this.newMember == '') {
        alert("请选择成员");
        return;
      }
      const selectedMember = this.newMember;
      try {
        await http.post('/api/members/add', {
          projectId: this.id,
          memberId: selectedMember
        })
        await this.fetchMembers(this.id);
        this.newMember = '';
      } catch (error) {
        this.newMember = '';
        console.error('Error adding new member:', error);
      }
    },
    async removeMember(projectId, memberId) {
        try {
          await http.delete(`/api/members/remove`, {
            params: {
              projectId: projectId,
              memberId: memberId
            }
          });
          // 从项目成员列表中移除成员
          await this.fetchMembers(this.id);
        } catch (error) {
          console.error('Error removing member:', error);
        }
      },
    getOngoingProject() {
      http.get("/api/projects/ongoing")
        .then(res => {
          this.tableData = res;
          console.log(res);
          if (res && res.length > 0) {
            this.getDetails(res[0]);
          }
        })
        .catch(error => {
          console.error("Error fetching ongoing projects:", error);
        })
    },

    getCompletedProject() {
      http.get("api/projects/completed")
        .then(res => {
          this.tableData = res;
          console.log(res);
          if (res && res.length > 0) {
            this.getDetails(res[0]);
          }
        })
        .catch(error => {
          console.error("Error fetching completed projects:", error);
        })
    },

    async fetchProjectDetails(projectId) {
      try {
        const res = await http.get(`/api/general/project/${projectId}`);
        this.projectDetails = res;
        console.log("Project details:", res);
      } catch (error) {
        console.error(`Error fetching project ${projectId} details:`, error);
      }
    },

    // 使用 ManagerTask.vue 中的任务接口
    async fetchProjectTasks(projectId) {
      try {
        const response = await http.get(`/api/tasks/project/${projectId}/tasks`);
        if (response) {
          this.projectTasks = response;
          console.log("获取到的任务数据:", this.projectTasks);
        } else {
          console.log("未获取到任务数据");
          this.projectTasks = [];
        }
      } catch (error) {
        console.error(`Error fetching tasks for project ${projectId}:`, error);
        this.$message.error('获取任务数据失败');
        this.projectTasks = [];
      }
    },

    initGanttChart() {
      if (this.ganttChart) {
        this.ganttChart.dispose();
      }

      const chartDom = this.$refs.ganttChart;
      if (!chartDom) {
        console.error('Cannot find gantt chart container');
        return;
      }

      this.ganttChart = echarts.init(chartDom);

      if (!this.projectTasks || this.projectTasks.length === 0) {
        console.warn('没有任务数据');
        return;
      }

      // 使用项目的开始和结束时间
      const projectStartDate = this.projectDetails.startDate ? new Date(this.projectDetails.startDate) : new Date();
      const projectEndDate = this.projectDetails.endDate ? new Date(this.projectDetails.endDate) : new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);

      // 首先创建任务数组并按开始时间排序
      const tasks = this.projectTasks
        .map(task => {
          const taskStartTime = task.startDate ? new Date(task.startDate) : projectStartDate;
          const taskEndTime = task.endDate ? new Date(task.endDate) : projectEndDate;

          return {
            name: task.memberName,
            status: (task.taskStatus === '待审核' || task.taskStatus === '已审核') ? 2 : 0,
            percentage: task.taskPercentage || 0,
            startTime: taskStartTime,
            endTime: taskEndTime
          };
        })
        .sort((a, b) => a.startTime - b.startTime); // 按开始时间升序排序

      console.log('处理后的排序任务数据:', tasks);

      // 抽取公共逻辑为辅助函数
      const getTaskDisplay = (task) => ({
        color: task.status === 2 ? '#67C23A' : '#909399',  // 已完成-绿色，未完成-灰色
        text: task.status === 2 ? '已完成' : '未完成',
        progress: task.status === 2 ? 100 : (task.percentage || 0)
      });

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            const task = tasks[params[0].dataIndex];
            const display = getTaskDisplay(task);

            return `
              <div style="padding: 3px;">
                <div>${task.name}</div>
                <div>开始时间: ${task.startTime.toLocaleDateString()}</div>
                <div>结束时间: ${task.endTime.toLocaleDateString()}</div>
                <div>权重: ${task.percentage}%</div>
                <div>状态: <span style="color:${display.color}">${display.text}</span></div>
              </div>
            `;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'time',
          axisLabel: {
            formatter: '{yyyy}-{MM}-{dd}'
          },
          splitLine: {
            show: true
          },
          min: projectStartDate.getTime(),
          max: projectEndDate.getTime(),
          interval: 24 * 3600 * 1000,
          axisPointer: {
            snap: true
          }
        },
        yAxis: {
          type: 'category',
          data: tasks.map(task => task.name) // 使用排序后的任务名称数组
        },
        series: [
          {
            // 背景进度条
            name: '任务进度',
            type: 'bar',
            stack: 'total',
            itemStyle: {
              color: params => {
                const task = tasks[params.dataIndex];
                return task.status === 2 ? '#67C23A' : '#909399';
              }
            },
            emphasis: {
              disabled: true
            },
            barWidth: 20,
            data: tasks.map(task => ({
              value: [
                task.endTime.getTime(),
                task.name,
                task.endTime.getTime()
              ],
            }))
          },
          {
            // 白色覆盖层
            name: '覆盖层',
            type: 'bar',
            stack: 'total',
            itemStyle: {
              color: '#f5f5f5'
            },
            emphasis: {
              disabled: true
            },
            barWidth: 20,
            data: tasks.map(task => ({
              value: [
                task.startTime.getTime(),
                task.name,
                task.startTime.getTime()
              ]
            })),
            tooltip: {
              show: false
            }
          }
        ]
      };

      console.log('图表数据:', {
        taskNames: option.yAxis.data,
        progressData: option.series[0].data,
        tasks: tasks
      });

      this.ganttChart.setOption(option);
    },

    formatDate(date) {
      return new Date(date).toLocaleDateString();
    }
  },
  created() {
    this.getOngoingProject();
    this.fetchAllMembers();
  },
  mounted() {
    window.addEventListener('resize', () => {
      if (this.ganttChart) {
        this.ganttChart.resize();
      }
    });
  },
  beforeDestroy() {
    if (this.ganttChart) {
      this.ganttChart.dispose();
    }
    window.removeEventListener('resize', () => {
      if (this.ganttChart) {
        this.ganttChart.resize();
      }
    });
  }
}
</script>

<style scoped>
.general-select {
  padding: 20px;
  background-color: #f0f2f5;
}

.project-list {
  max-height: 800px;
  overflow-y: auto;
}

.project-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-bordered {
  border: none;
  /* 移除默认边框，使用El-Card的阴影 */
}

.project-column .cell {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.project-details {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f7f9fb;
  border-bottom: 1px solid #ebeef5;
  padding: 10px 20px;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.gantt-card,
.info-card {
  margin-bottom: 20px;
}

.gantt-container {
  width: 100%;
  height: 400px;
  background-color: #fafafa;
  border-radius: 4px;
}

.el-descriptions {
  background-color: #fff;
}

.el-descriptions-item__label {
  color: #606266;
  font-weight: bold;
}

.el-descriptions-item__content {
  color: #303133;
}
</style>

<style>
/* 全局样式增强 */
body {
  background-color: #f0f2f5;
}

h1,
h2 {
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
</style>
